package com.heima.admin.interceptor;

import com.heima.common.exception.CustomException;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.thread.AdminThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class AdminTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登录就直接放行
        if(request.getRequestURI().contains("/login")){
            return true;
        }
        //获取请求头中的userId
        String userId = request.getHeader("userId");
        if (StringUtils.isBlank(userId)) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //将用户的id存如到ThreadLocal
        AdUser adUser = new AdUser();
        adUser.setId(Integer.valueOf(userId));
        AdminThreadLocalUtil.setUser(adUser);
        //放行
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理ThreadLocal
        AdminThreadLocalUtil.clear();
    }
}
